package com.czb.seckill.controller;

import com.czb.seckill.pojo.User;
import com.czb.seckill.service.GoodsService;
import com.czb.seckill.service.UserService;
import com.czb.seckill.vo.GoodsVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author: 陈正彬
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    //装配UserService
    @Resource
    private UserService userService;

    //装配GoodsService
    @Resource
    private GoodsService goodsService;

    //装配RedisTemplate
    @Resource
    private RedisTemplate redisTemplate;

    //手动渲染需要的模板解析器
    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;


//    //进入到商品列表页面，到DB查询
//    @RequestMapping("/toList")
////    public String toList(HttpSession session, Model model,
////                         @CookieValue("userTicket") String ticket) {
////    public String toList(Model model,
////                         @CookieValue("userTicket") String ticket,
////                         HttpServletRequest request, HttpServletResponse response) {
//    //改用解析器完成
//    public String toList(Model model, User user) {
//
//        //如果cookie没有生成
////        if (!StringUtils.hasText(ticket)) {
////            return "login";
////        }
////
////        //通过ticket获取session中存放的user
//////        User user = (User) session.getAttribute(ticket);
////        //从redis获取用户
////        User user = userService.getUserByCookie(ticket, request, response);
//        if (null == user) {
//            return "login"; //用户没有成功登入
//        }
//
//        //将user放入model，携带给下一个模板使用
//        model.addAttribute("user", user);
//        //将商品列表信息，放入到model，携带给下一个模板使用
//        model.addAttribute("goodsList",goodsService.findGoodsVo());
//
//        return "goodsList";
//
//    }

    //进入到商品列表页面，使用redis优化
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf8")
    @ResponseBody
    //改用解析器完成
    public String toList(Model model, User user, HttpServletRequest request,
                         HttpServletResponse response) {

        if (null == user) {
            return "login"; //用户没有成功登入
        }
        //先到redis获取页面,有就直接返回
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        if (StringUtils.hasText(html)) {
            return html;
        }

        //将user放入model，携带给下一个模板使用
        model.addAttribute("user", user);
        //将商品列表信息，放入到model，携带给下一个模板使用
        model.addAttribute("goodsList", goodsService.findGoodsVo());

        //如果从redis获取的页面为空,就手动渲染，存入到redis
        WebContext webContext =
                new WebContext(request, response, request.getServletContext(),
                        request.getLocale(), model.asMap());

        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if (StringUtils.hasText(html)) {
            //将页面保存到redis，设置每60秒更新一次(该页面60秒会失效，redis会清楚该页面)
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }

        return html;

    }

//    //方法，进入到商品详情页面,到DB查询
//    @RequestMapping("/toDetail/{goodsId}")
//    public String toDetail(Model model, User user, @PathVariable Long goodsId) {
//
//        if (null == user) {
//            //没有登入
//            return "login";
//        }
//        //将user放入model
//        model.addAttribute("user", user);
//        //通过goodsId获取秒杀商品的信息
//        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
//        //将goodsVo放入model
//        model.addAttribute("goods", goodsVo);
//
//        //返回秒杀商品详情时，同时返回该商品的秒杀状态和秒杀剩余的时间
//        //变量 seckillStatus 秒杀状态 0：秒杀未开始，1：秒杀中， 2：秒杀已结束
//        //变量 remainSeconds 剩余秒数 >0：表示还有多久开始秒杀，0：表示秒杀进行中，-1：表示秒杀已经结束
//        int secKillStatus = 0;
//        int remainSeconds = 0;
//        //秒杀开始时间
//        Date startDate = goodsVo.getStartDate();
//        //秒杀结束时间
//        Date endDate = goodsVo.getEndDate();
//        //当前时间
//        Date nowDate = new Date();
//        //还未开始秒杀
//        if (nowDate.before(startDate)) {
//            //得到还有多久开始秒杀
//            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
//
//        } else if (nowDate.after(endDate)) {//秒杀已经结束
//            secKillStatus = 2;
//            remainSeconds = -1;
//        } else {//秒杀中
//            secKillStatus = 1;
//            remainSeconds = 0;
//        }
//        //将seckillStatus 和 remainSeconds放入到model，携带给模板页使用
//        model.addAttribute("secKillStatus", secKillStatus);
//        model.addAttribute("remainSeconds", remainSeconds);
//
//        return "goodsDetail";
//    }

    //方法，进入到商品详情页面,使用redis优化
    @RequestMapping(value = "/toDetail/{goodsId}",produces = "text/html;charset=utf8")
    @ResponseBody
    public String toDetail(Model model, User user, @PathVariable Long goodsId,
                           HttpServletRequest request, HttpServletResponse response) {

        if (null == user) {
            //没有登入
            return "login";
        }

        //先到redis获取页面，如果有就返回
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail:" + goodsId);
        if (StringUtils.hasText(html)) {
            return html;
        }

        //将user放入model
        model.addAttribute("user", user);
        //通过goodsId获取秒杀商品的信息
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        //将goodsVo放入model
        model.addAttribute("goods", goodsVo);

        //返回秒杀商品详情时，同时返回该商品的秒杀状态和秒杀剩余的时间
        //变量 seckillStatus 秒杀状态 0：秒杀未开始，1：秒杀中， 2：秒杀已结束
        //变量 remainSeconds 剩余秒数 >0：表示还有多久开始秒杀，0：表示秒杀进行中，-1：表示秒杀已经结束
        int secKillStatus = 0;
        int remainSeconds = 0;
        //秒杀开始时间
        Date startDate = goodsVo.getStartDate();
        //秒杀结束时间
        Date endDate = goodsVo.getEndDate();
        //当前时间
        Date nowDate = new Date();
        //还未开始秒杀
        if (nowDate.before(startDate)) {
            //得到还有多久开始秒杀
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);

        } else if (nowDate.after(endDate)) {//秒杀已经结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {//秒杀中
            secKillStatus = 1;
            remainSeconds = 0;
        }
        //将seckillStatus 和 remainSeconds放入到model，携带给模板页使用
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds", remainSeconds);

        //如果从redis获取的页面为空,就手动渲染，存入到redis
        WebContext webContext =
                new WebContext(request, response, request.getServletContext(),
                        request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);

        if (StringUtils.hasText(html)) {
            valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
        }
        return html;
    }
}
